
class Admin::WikiController < Admin::BaseController

  before_action :find_wiki, only: [:edit, :update, :destroy]

  def index
    @wikis = Wiki.with_deleted.paginate(page: params[:page] || 1, per_page: params[:per_page] || 15).order("id desc")
  end

  def new
    @wiki = Wiki.new
  end

  def create
    wiki_params = params.require(:wiki).permit!
    wiki_params[:first_img] = get_first_img(wiki_params)
    @wiki = Wiki.new(wiki_params)
    @wiki.tag_list = wiki_params[:fake_tag_list].split(/\r\n/).join(",")
    if @wiki.save
      flash[:notice] = "新建百科成功"
      redirect_to admin_wiki_index_path
    else
      flash[:notice] = "新建百科失败"
      render action: :new
    end
  end

  def edit
    render action: :new
  end

  def update
    wiki_params = params.require(:wiki).permit!
    wiki_params[:first_img] = get_first_img(wiki_params)
    @wiki.attributes = wiki_params
    @wiki.tag_list = wiki_params[:fake_tag_list].split(/\r\n/).join(",")

    if @wiki.save
      flash[:notice] = "修改百科成功"
      redirect_to admin_wiki_index_path
    else
      flash[:notice] = "修改百科失败"
      redirect_to :back
    end
  end

  def destroy
    begin
      @wiki.destroy
      flash[:notice] = "修改百科成功"
      redirect_to admin_wiki_index_path
    rescue
      flash[:notice] = "修改百科失败"
      redirect_to :back
    end
  end

  private

  def get_first_img wiki_params
    doc = Nokogiri::HTML(wiki_params[:content], nil, "UTF-8")
    img = doc.at('img')
    if img.present?
      img['src']
    else
      nil
    end
  end

  def find_wiki
    @wiki = Wiki.with_deleted.find params[:id]
  end

end
